package com.safe.first.infrastructure.interceptor;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import com.google.common.base.Strings;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;

/**
 * @author Mickey
 * @since 2022/6/11
 **/
@Component
public class MySecurityContextRepository implements SecurityContextRepository {

    @Override
    public boolean containsContext(HttpServletRequest request) {
        return false;
    }

    @Override
    public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
        String authorization = requestResponseHolder.getRequest().getHeader("Authorization");
        if (Strings.isNullOrEmpty(authorization)) {
            return new SecurityContextImpl(null);
        }
        String token = authorization.replace("Bearer ", "");
        JWT jwt = JWT.of(token);
        JWTPayload payload = jwt.getPayload();
        Object login_user_key = payload.getClaim("uid");

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken("dd", "dd", new ArrayList<>());
        return new SecurityContextImpl(usernamePasswordAuthenticationToken);
    }

    @Override
    public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) {
    }
}
